<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

abstract class BaseApiController extends Controller
{
    /**
     * 从param对象中获取参数值
     *
     * @param Request $request
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    protected function getParam(Request $request, string $key, $default = null)
    {
        // 优先从param对象中获取
        $param = $request->input('param', []);
        if (is_array($param) && isset($param[$key])) {
            return $param[$key];
        }
        
        // 如果param中没有，则从根级别获取（兼容性）
        return $request->input($key, $default);
    }

    /**
     * 从param对象中获取多个参数
     *
     * @param Request $request
     * @param array $keys
     * @return array
     */
    protected function getParams(Request $request, array $keys): array
    {
        $params = [];
        foreach ($keys as $key) {
            $params[$key] = $this->getParam($request, $key);
        }
        return $params;
    }

    /**
     * 从param对象中获取必填参数，如果缺失则抛出异常
     *
     * @param Request $request
     * @param string $key
     * @param string $message
     * @return mixed
     * @throws \InvalidArgumentException
     */
    protected function getRequiredParam(Request $request, string $key, string $message = null)
    {
        $value = $this->getParam($request, $key);
        
        if (empty($value)) {
            $message = $message ?: "缺少必填参数: {$key}";
            throw new \InvalidArgumentException($message);
        }
        
        return $value;
    }
}
